package com.company.nuwa.common.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterOutputStream;

/**
 * <p>字符串压缩</p>
 *
 * @author Lionel Lee
 * @version 1.0: ZipUtils.java
 * @date 2021/5/21 7:40 下午
 */
@Slf4j
public class ZipUtils {

    /**
     * 压缩字符串,默认梳utf-8
     *
     * @param text 字符串
     * @return  String
     */
    @SneakyThrows
    public static String zipBase64(String text) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            try (DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(out)) {
                deflaterOutputStream.write(text.getBytes(StandardCharsets.UTF_8));
            }
            return Base64Utils.encodeToString(out.toByteArray());
        }
    }

    /**
     * 解压字符串,默认utf-8
     *
     * @param text 字符串
     * @return String
     */
    @SneakyThrows
    public static String unzipBase64(String text) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            try (OutputStream outputStream = new InflaterOutputStream(os)) {
                outputStream.write(Base64Utils.decodeFromString(text));
            }
            return new String(os.toByteArray(), StandardCharsets.UTF_8);
        }
    }
}